import Web3 from 'web3'
import $cookies from 'vue-cookies'
import WalletConnectProvider from '@walletconnect/web3-provider'
import {
  Message
} from 'element-ui'
// var ethUtil = require('ethereumjs-util')
// var sigUtil = require('eth-sig-util')
/* eslint-disable */

let from_addr = ''
// let bsc_MyContract = '0x254871f07ce0f27fAb84F96cD6a326F9c96fF191' // bsc测试
// let eth_MyContract = '0x4c4cC095c3321688BDb31F744835A8736609fb1b' // eth测试
// let polygon_MyContract = '0x1FFf4027212fa47bbe3223e343046A5453fF1016' // polygon测试
// // let mint_cun_test = "0x1FFf4027212fa47bbe3223e343046A5453fF1016"    //cun测试
// let myContractInstance
// var gashash = [],
// let $cookies = this.$cookies
var _gasthis = this
// const toHex = (num) => {
//   return '0x' + num.toString(16)
// }
class Web3Tool {
  constructor () {
    _gasthis = this
    _gasthis.init_web3(1)
  }

  // 二维码退出登录
  async WalletConnect_del () {
    if ($cookies.get('wall_type') === 2 || $cookies.get('wall_type') === '2') {
    await this.provider.disconnect()
    } else {
      ethereum = window.ethereum
      web3 = new Web3(ethereum)
      // console.log(web3, 'web3')
      // console.log(ethereum.enable())
      await ethereum.on('disconnect', (error) => {
        console.log(error, 'disconnect')
      })
    }
    $cookies.remove('wall_type')
    $cookies.remove('wallet_acount')
  }
  async init_web3 (change) {
    const that = this
    // console.log(this.$cookies.get('wall_type'))
    if ($cookies.get('wall_type') === 2 || $cookies.get('wall_type') === '2') { // 二维码登录
      that.provider = new WalletConnectProvider({
        rpc: {
          1: 'https://mainnet.infura.io/v3/9c58fe08a1e348e2be986a43f48902f4',
          56: 'https://data-seed-prebsc-1-s1.binance.org:8545/',
          97: 'https://data-seed-prebsc-1-s3.binance.org:8545',
          3: 'https://ropsten.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161',
          4: 'https://rinkeby.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161'
        }
      })
      that.provider.on('accountsChanged', (accounts) => {
        // console.log(accounts)
        $cookies.set('wallet_acount', accounts)
      })
      that.provider.on('chainChanged', (chainId) => {
        // console.log(chainId)
      })
      // console.log('用户监听变化')

      that.web3 = new Web3(that.provider)
      const networkId = new that.web3.eth.net.getId()
      await that.provider.enable().then(function (accounts) {
          console.log(accounts)
          that.from_addr = accounts[0]
        })
        .catch(function (reason) {
          that.from_addr = ''
          // console.log('登录不成功')
          $cookies.set('wall_type', '')
          return false
        })
      return that.from_addr
    } else if ($cookies.get('wall_type') === 1 || $cookies.get('wall_type') === '1') {
      if (window.ethereum) {
        // console.log(1)
        that.ethereum = window.ethereum
        that.web3 = new Web3(that.ethereum)
        that.ethereum.autoRefreshOnNetworkChange = true
        that.accounts = await that.ethereum.request({
          method: 'eth_requestAccounts'
        })
        that.account = that.accounts[0]
        // console.log(that.accounts)
        $cookies.set('wallet_acount', that.account)
        // if (change != 1) {
        await that.ethereum.enable()
          .then(function (accounts) {
            that.from_addr = accounts[0]
            // console.log(2, that.from_addr)
          })
          .catch(function (reason) {
            // console.log(3)
            return false
          })
        // }
        that.listening_web3()
        // 用户变化监听
        that.ethereum.on('accountsChanged', async function (accounts) {
          $cookies.set('wallet_acount', accounts[0])
          // console.log($cookies.get('wallet_acount'), accounts)
          // await _gasthis.getBalance()
          // await _gasthis.getPrice($cookies.get('wallet_chain'))
          that.from_addr = accounts[0]
          _gasthis.account_listen(from_addr)
          // location.reload()
          // console.log(accounts[0])
        })
        // 网络变化监听
        that.ethereum.on('networkChanged', async function (result) {
          // console.log(4)
          // let arr= [1,56,97,114]
          // if(arr.indexOf(result) >=0){
          // console.log(result)
          $cookies.set('wallet_chain', result)
          // await _gasthis.getBalance();
          // await _gasthis.getPrice(result);
          // location.reload();
          // }
        })
        // this.account_listen(from_addr)
        window.dispatchEvent(
          new CustomEvent('wallet_change', {
            detail: {
              params: from_addr
            }
          })
        )
        // console.log(5)
        return true
      } else if (window.web3) {
        console.log(6)
        that.web3 = new Web3(that.web3.currentProvider)
        that.listening_web3()
        return true
      } else {
        console.log(7)
        return false
      }
    }
  }
  // init web3 singin
  async initWeb3SingIn () {
    var _web3 = await init_web3_singIn()
    // console.log('web3.eth.coinbase == ')
    return _web3
  }
  account_listen (account) {
    window.dispatchEvent(
      new CustomEvent('wallet_change', {
        detail: {
          params: this.from_addr
        }
      })
    )
  }

  listening_web3 () {
    this.web3.eth.net.isListening().then((result) => {
      // //console.log( '您正在监听网络：', result );
    })
    this.web3.eth.net.getId().then((result) => {
      // //console.log( '您当前网络ID：', result );
      // eth_net_id = result;
    })
  }

  async init_web3_singIn () {
    if (window.ethereum) {
      this.ethereum = window.ethereum
      this.ethereum.autoRefreshOnNetworkChange = true
      this.web3 = new Web3(this.ethereum)
      this.ethereum.enable()
        .catch(function (reason) {
          // 如果用户拒绝了登录请求
          if (reason === 'User rejected provider access') {
            // 用户拒绝登录后执行语句；
          } else {
            // 本不该执行到这里，但是真到这里了，说明发生了意外
            Message.warning('There was a problem signing you in')
          }
        }).then(function (accounts) {
          // 判断是否连接以太
          // if (ethereum.networkVersion !== desiredNetwork) {}
          // let currentProvider = web3.currentProvider;
          // web3.setProvider(currentProvider);
          // 如果用户同意了登录请求，你就可以拿到用户的账号
          // web3.eth.defaultAccount = accounts[0];

          // this.web3_ob = new Web3(new Web3.providers.HttpProvider("https://data-seed-prebsc-2-s3.binance.org:8545/"));
          // myContract = new web3.eth.Contract(ABI, metaMaskAddress);
          // 这里返回用户钱包地址
          // callback(accounts[0]);
          return true
        })
      listening_web3()
      // console.log( 'this.web3', this.web3 );
      return true
    } else if (window.web3) {
      this.web3 = new Web3(this.web3.currentProvider)
      listening_web3()
      return true
    } else {
      return false
    }
  }

  // 获取地址 singin
  async getEthAddrInfoSingIn () {
    // console.log(this.web3)
    var _verify = ''
    if ($cookies.get('wall_type') === 2) {
      _verify = await verifyWeb3AddrSingIn()
    } else if ($cookies.get('wall_type') === 1) {
      if (this.web3) {
        _verify = await verifyWeb3AddrSingIn()
      }
    }
    return from_addr
  }

  // 验证 web3 singin
  async verifyWeb3AddrSingIn () {
    var _web3 = await init_web3()
    // console.log(_web3, '==' + from_addr)
    return true
  }

  // 网站 singin
  // sign_web (_nonce, _sign_web_callback) {
  //   var text = 'CUN uses this cryptographic signature in place of a password, verifying that you are the owner of this Ethereum address. I am signing my one-time nonce: ' + _nonce
  //   var msg = ethUtil.bufferToHex(new Buffer(text, 'utf8'))
  //   // console.log(msg)
  //   // var from = web3.eth.accounts[0]
  //   var from = from_addr
  //   // console.log('CLICKED, SENDING PERSONAL SIGN REQ')
  //   var params = [msg, from]
  //   var method = 'personal_sign'

  //   this.web3.currentProvider.sendAsync({
  //     method,
  //     params,
  //     from
  //   }, function (err, result) {
  //     if (err) return console.error(err)
  //     if (result.error) return console.error(result.error)

  //     const msgParams = { data: msg }
  //     msgParams.sig = result.result
  //     const recovered = sigUtil.recoverPersonalSignature(msgParams)

  //     if (recovered === from||recovered === from.toLowerCase()) {
  //       // console.log('SigUtil Successfully verified signer as ' + from)
  //       // window.alert('SigUtil Successfully verified signer as ' + from)
  //       _sign_web_callback(result.result)
  //     } else {
  //       console.dir(recovered)
  //       // console.log('SigUtil Failed to verify signer when comparing ' + recovered.result + ' to ' + from)
  //       // console.log('Failed, comparing %s to %s', recovered, from)
  //     }

  //   })
  // }
  // 交换cunp
  // exchangeCunp(val,chain_id){
  //     this.base_transaction = {
  //       'from': from_addr,
  //       'gas': 50 * 10000, // 接收方地址
  //       // 'value': (Number(web3Tool.web3.utils.toWei((parseFloat(val)).toString(), 'ether')))
  //       'value': val
  //     }
  //     let MyContract = "";
  //   if(chain_id == 56 || chain_id == 97){
  //     MyContract = bsc_MyContract
  //   }else if(chain_id == 114 || chain_id == 80001){
  //     MyContract = polygon_MyContract
  //   }else{
  //     MyContract = eth_MyContract
  //   }

  //   // return false;
  //     myContractInstance = new this.web3.eth.Contract(abi,MyContract);
  //     myContractInstance.methods.acceptCoin().send(this.base_transaction)
  //     .on('transactionHash', function (hash) {
  //       // console.log(1111)
  //       // console.log(hash);
  //     })
  //     .on('receipt', function (receipt) {
  //       // console.log(2222)
  //       console.log(receipt)
  //     })
  //     .on('error', function (error) {
  //       // console.log(333333)
  //       // console.log(error)
  //     })
  // }

  // 查看价格
  // async getPrice(chain_id,price,_callback){
  //   console.log(chain_id)
  //   let MyContract = "";
  //   if(chain_id == 56 || chain_id == 97){
  //     MyContract = bsc_MyContract
  //   }else if(chain_id == 114){
  //     MyContract = polygon_MyContract
  //   }else{
  //     MyContract = eth_MyContract
  //   }
  //   myContractInstance = new this.web3.eth.Contract(abi,MyContract);
  //   // console.log("检测变化")
  //   // console.log(myContractInstance)
  //   myContractInstance.methods.getLatestPrice().call().then((result) => {
  //     console.log(result)
  //     let stage= $cookies.get('exchange_stage')
  //     let exchange_radio = 0;
  //     if(stage == 1){
  //       exchange_radio =  100000000/(result * 2)
  //     }else if(stage == 2){
  //       exchange_radio =  100000000/result
  //     }else if(stage == 3){
  //       exchange_radio =  100000000/(result/2)
  //     }
  //     $cookies.set('exchange_radio',exchange_radio.toFixed(5))
  //     console.log($cookies.get('exchange_radio'))
  //     if(price){
  //       _callback(price,result)
  //     }
  //   })
  // ß

  // 获取账户余额
  async getBalance(){
    from_addr = $cookies.get('wallet_acount')
    if(from_addr == ""){
      Message.error("账户未登录,请先进行登录", '', {})
      return false
    }
    console.log(this.web3)

    this.web3.eth.getBalance(from_addr).then(
      function(result){
        console.log('getBalance', result)
        // $cookies.set('wallet_acount_balance',(result/1000000000000000000).toFixed(5))
      });
  }

  // tranferCunp(to,value){
  //   this.web3.eth.sendTransaction({
  //     from: from_addr,
  //     to: to,
  //     value: value
  //   })
  //     //点击确定获取hash值
  //   .on('transactionHash', function(hash){
  //   })
  //   //成功后方法
  //   .on('receipt', function(receipt){
  //   })
  //   //失败方法
  //   .on('error', function (error) {
  //   })

  // }

  // getCunBalance(from_addr){
  //   web3.givenProvider = 'https://http-mainnet-rpc.coopunion.net/';
  //   let new_web3 = new Web3(Web3.givenProvider || "https://http-mainnet-rpc.coopunion.net/");
  //   new_web3.eth.getBalance(from_addr).then(
  //     function(result){
  //       console.log(result)
  //       // $cookies.set('wallet_acount_balance',(result/1000000000000000000).toFixed(5))
  //     });
  // }

  // addOrChangeNetWork(params){
  //   let chain = {
  //     "name": "Rinkeby",
  //     "title": "Ethereum Testnet Rinkeby",
  //     "chain": "ETH",
  //     "rpc": [
  //       "https://rinkeby.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161",
  //       "wss://rinkeby.infura.io/ws/v3/9aa3d95b3bc440fa88ea12eaa4456161"
  //     ],
  //     "faucets": [],
  //     "nativeCurrency": {
  //       "name": "Rinkeby Ether",
  //       "symbol": "RIN",
  //       "decimals": 18
  //     },
  //     "infoURL": "https://www.rinkeby.io",
  //     "shortName": "rin",
  //     "chainId": 4,
  //     "networkId": 4,
  //     "ens": {
  //       "registry": "0xe7410170f87102df0055eb195163a03b7f2bff4a"
  //     },
  //     "explorers": [
  //       {
  //         "name": "etherscan-rinkeby",
  //         "url": "https://rinkeby.etherscan.io",
  //         "standard": "EIP3091"
  //       }
  //     ]
  //   }
  //  let net_data = {
  //     chainId: toHex(chain.chainId), // A 0x-prefixed hexadecimal string
  //     chainName: chain.name,
  //     nativeCurrency: {
  //       name: chain.nativeCurrency.name,
  //       symbol: chain.nativeCurrency.symbol, // 2-6 characters long
  //       decimals: chain.nativeCurrency.decimals,
  //     },
  //     rpcUrls: chain.rpc,
  //     blockExplorerUrls: [ ((chain.explorers && chain.explorers.length > 0 && chain.explorers[0].url) ? chain.explorers[0].url : chain.infoURL) ]
  //   }

  //   this.web3.eth.getAccounts((error, accounts) => {
  //     window.ethereum.request({
  //       method: 'wallet_addEthereumChain',
  //       params: [net_data, accounts[0]],
  //     })
  //     .then((result) => {
  //       console.log(1111111111)
  //       console.log(result)
  //     })
  //     .catch((error) => {
  //       console.log(2222222222)
  //       // stores.emitter.emit(ERROR, error.message ? error.message : error)
  //       console.log(error)
  //     });
  //   })
  // }
}

let web3Tool = new Web3Tool()
export default web3Tool
